package com.haizhi.workstation.interceptor;


import com.alibaba.fastjson.JSON;
import com.haizhi.workstation.annotation.AccessLimit;
import com.haizhi.workstation.redis.RedisServer;
import com.haizhi.workstation.redis.key.AccessLimitKeyPrefix;
import com.haizhi.workstation.result.CodeMsg;
import com.haizhi.workstation.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class AccessLimitInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private RedisServer redisServer;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            AccessLimit accessLimit = handlerMethod.getMethodAnnotation(AccessLimit.class);
            //访问的方法接口,作为key的组成部分,避免不同方法接口之间访问互不影响
            String methodName = handlerMethod.getMethod().getName();

            if(accessLimit!=null){//如果贴了AccessLimit注解
                String requestUrl = request.getParameter("requestUrl");
                String responseUrl = request.getRemoteAddr()/*+":"+request.getRemotePort()*/;
                int seconds = accessLimit.seconds();//注解限制的时间范围
                int maxCount = accessLimit.maxCount();//注解限制时间范围内的访问次数
                if(seconds > 0 && maxCount > 0) {
                    String keyPrefix = "responseUrl:"+responseUrl+":methodName:"+methodName;
                    Long count;
                    AccessLimitKeyPrefix key = new AccessLimitKeyPrefix(keyPrefix,seconds);
                    //当前限制的请求路径
                    String uri = request.getRequestURI();
                    log.info("============="+uri);
                    if(redisServer.exists(key,uri)){
                        count = redisServer.incr(key,uri);
                    }else{
                        count = redisServer.incr(key,uri);
                        redisServer.expire(key,uri,seconds);
                    }
                    if(count>maxCount){
                        renderResponse(response, Result.error(CodeMsg.ACCESS_LIMIT));
                        return false;
                    }
                }
            }
        }
        return true;
    }

    public void renderResponse(HttpServletResponse response, Result error) throws IOException {
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(error));
    }
}
